package edu.tyut.game.ui.user.register

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import cn.hutool.crypto.digest.DigestUtil
import edu.tyut.game.databinding.ActivityRegisterBinding
import edu.tyut.game.logic.UserRepository
import edu.tyut.game.logic.model.User
import edu.tyut.game.ui.user.SharedViewModel
import edu.tyut.game.ui.user.login.LoginActivity
import edu.tyut.game.utils.LogUtils
import edu.tyut.game.utils.RegexUtils
import edu.tyut.game.utils.StatusBarUtils

class RegisterActivity : AppCompatActivity() {

    private val tag = "RegisterActivity"

    private lateinit var binding: ActivityRegisterBinding

    private val viewModel by lazy {
        ViewModelProvider(this)[RegisterViewModel::class.java]
    }
    private val shareViewModel by lazy {
        ViewModelProvider(this)[SharedViewModel::class.java]
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRegisterBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 隐藏ActionBar
        // 状态栏透明
        StatusBarUtils.setTranslucentStatusBar(this)

        // 注册功能监听
        viewModel.registerUser.observe(this) { result ->
            LogUtils.d(tag, result.toString())
        }

        // 性别默认为 男
        var gender = "男"
        binding.manWomenGroup.setOnCheckedChangeListener { _, checkedId ->
            gender = when (checkedId) {
                binding.man.id -> "男"
                else -> "女"
            }
        }

        // 监听注册数据
        // 用户名
        var usernameFlag = false
        binding.username.requestFocus() // 获取焦点
        binding.username.setOnFocusChangeListener { v, hasFocus ->
            // 发送一条请求确认用户名是否已经存在
            if (!hasFocus) {
                val editText = v as EditText
                val username = editText.text.toString().trim()
                // 存入viewModel
                viewModel.username = username
                // 绑定到viewModel
                binding.username.setText(viewModel.username)
                if (username.isEmpty()) {
                    usernameFlag = false
                    Toast.makeText(this, "用户名不能为空!", Toast.LENGTH_SHORT).show()
                } else if (!RegexUtils.userNameMatches(username)) {
                    usernameFlag = false
                    Toast.makeText(
                        this,
                        "用户名必须是: 中文, 英文, 数字, 下划线, 长度1–25",
                        Toast.LENGTH_SHORT
                    )
                        .show()
                } else {
                    val user = User(0, username, "", "", "", null, null)
                    viewModel.isExistUser(user)
                    usernameFlag = true
                }
            }
        }
        // 密码
        var passwordFlag = false
        binding.password.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                val editText = v as EditText
                val password = editText.text.toString().trim()
                // 存入viewModel
                viewModel.password = password
                // 绑定到viewModel
                binding.password.setText(viewModel.password)
                if (password.isEmpty()) {
                    passwordFlag = false
                    Toast.makeText(this, "密码不能为空!", Toast.LENGTH_SHORT).show()
                } else if (!RegexUtils.passwordMatches(password)) {
                    passwordFlag = false
                    Toast.makeText(
                        this,
                        "密码必须是: 必须字母开头, 可以包含 .~!@#\$%^& +-*/= 特殊字符, 数字,字母,下划线,长度5–17",
                        Toast.LENGTH_SHORT
                    ).show()
                } else {
                    passwordFlag = true
                }
            }
        }
        // 确认密码
        var confirmPasswordFlag = false
        binding.confirmPassword.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                val editText = v as EditText
                val password = binding.password.text.toString().trim()
                val confirmPassword = editText.text.toString().trim()
                // 存入viewModel
                viewModel.confirmPassword = confirmPassword
                // 绑定到viewModel
                binding.confirmPassword.setText(viewModel.confirmPassword)
                if (password != confirmPassword) {
                    confirmPasswordFlag = false
                    Toast.makeText(this, "请确保两次输入的密码相同!", Toast.LENGTH_SHORT).show()
                } else {
                    confirmPasswordFlag = true
                }
            }
        }
        // 邮箱
        var emailFlag = false
        binding.email.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                val editText = v as EditText
                val email = editText.text.toString().trim()
                // 存入viewModel
                viewModel.email = email
                // 绑定到viewModel
                binding.email.setText(viewModel.email)
                if (email.isEmpty()) {
                    emailFlag = false
                    Toast.makeText(this, "邮箱不能为空!", Toast.LENGTH_SHORT).show()
                } else if (!RegexUtils.emailMatches(email)) {
                    emailFlag = false
                    Toast.makeText(this, "请输入正邮箱!", Toast.LENGTH_SHORT).show()
                } else {
                    emailFlag = true
                }
            }
        }
        // 验证码
        var webCode: String? = null
        viewModel.sendMailData.observe(this) { result ->
            if (result.isSuccess) {
                webCode = result.getOrNull()
                LogUtils.d(tag, "网络验证码：$webCode")
            }
        }
        // 获取验证码
        binding.getVerificationCode.setOnClickListener {

            val button = it as Button
            button.isFocusable = true
            button.isFocusableInTouchMode = true
            button.requestFocus(View.FOCUS_DOWN)

            val user = viewModel.run {
                User(0, username, password, gender, email, null, null)
            }
            if (usernameFlag and emailFlag) {
                // 发送邮件
                viewModel.sendMail(user)
                LogUtils.d(tag, user.toString())
                // 开启协程读秒 60s
                shareViewModel.countDown(60000, button)
            } else {
                Toast.makeText(this, "请填写完整的用户名和邮箱信息!", Toast.LENGTH_SHORT).show()
            }
        }
        shareViewModel.second.observe(this) {
            binding.getVerificationCode.text = "${it}s"
        }
        // 验证验证码
        var codeFlag = false
        binding.verificationCode.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                val editText = v as EditText
                val code = editText.text.toString().trim()
                LogUtils.d(tag, code)
                // 保存至viewModel
                viewModel.verificationCode = code
                // 绑定到viewModel
                binding.verificationCode.setText(viewModel.verificationCode)
                codeFlag = if (code.isEmpty()) {
                    Toast.makeText(this, "请输入验证码!", Toast.LENGTH_SHORT).show()
                    false
                } else
                    webCode == code

                LogUtils.d(tag, codeFlag.toString())
                LogUtils.d(tag, "webCode: $webCode")
                LogUtils.d(tag, "code: $code")
            }
        }

        // 注册
        binding.register.setOnClickListener {

            val button = it as Button
            button.isFocusable = true
            button.isFocusableInTouchMode = true
            button.requestFocus(View.FOCUS_DOWN)

            val flag =
                usernameFlag and passwordFlag and confirmPasswordFlag and emailFlag and codeFlag

            val username = binding.username.text.toString().trim()
            val password = binding.password.text.toString().trim()
            val email = binding.email.text.toString().trim()

            // ================================
            if (!usernameFlag) {
                Toast.makeText(
                    this,
                    "用户名必须是: 中文, 英文, 数字, 下划线, 长度1–25",
                    Toast.LENGTH_SHORT
                )
                    .show()
            }
            if (!passwordFlag) {
                Toast.makeText(
                    this,
                    "密码必须是: 必须字母开头, 可以包含 .~!@#\$%^& +-*/= 特殊字符, 数字,字母,下划线,长度5–17",
                    Toast.LENGTH_SHORT
                ).show()
            }
            if (!confirmPasswordFlag) {
                Toast.makeText(this, "请确保两次输入的密码相同!", Toast.LENGTH_SHORT).show()
            }
            if (!emailFlag) Toast.makeText(this, "请输入正确邮箱!", Toast.LENGTH_SHORT).show()
            if (!codeFlag) Toast.makeText(this, "请输入正确验证码!", Toast.LENGTH_SHORT).show()
            // ==========================================

            if (flag) {
                // 对密码进行加密
                val digestPassword = DigestUtil.sha256Hex(password)
                LogUtils.d(tag, digestPassword)
                val user = User(0, username, digestPassword, gender, email, null, null)
                viewModel.register(user)
                LoginActivity.actionStart(this)
                Toast.makeText(this, "注册成功!", Toast.LENGTH_LONG).show()
                this.finish()
                LogUtils.d(tag, user.toString())
                LogUtils.d(tag, "注册！！！")
            }
        }

        // 用户名观察者
        viewModel.existUser.observe(this) { result ->
            LogUtils.d(tag, result.toString())
            if (result.isFailure) {
                binding.register.isEnabled = false
                Toast.makeText(this, "请检查您的网络!", Toast.LENGTH_LONG).show()
            } else if (result.getOrNull() == true) {
                binding.register.isEnabled = false
                Toast.makeText(this, "用户名已存在!", Toast.LENGTH_LONG).show()
            } else {
                binding.register.isEnabled = true
            }
        }
    }

    // 别的Activity启动LoginActivity
    companion object {
        fun actionStart(context: Context) {
            val intent = Intent(context, RegisterActivity::class.java)
            context.startActivity(intent)
        }
    }
}